package com.hundsun.fcp.webplugin.service;

import android.content.Context;

import com.hundsun.fcp.common.logger.AndroidLogger;
import com.hundsun.fcp.common.logger.Logger;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

public abstract class FcpDataServiceBase extends AsyncHttpResponseHandler {
	private static Logger logger = AndroidLogger.getLogger() ;

	private static final int RETRY_TIMES = 2;
	private static final int SOCK_TIMEOUT = 60000;
	private static final String USER_AGENT = "fcp.client.android.";
	private AsyncHttpClient mAsyncHttpClient;
	private Context mContext;

	private IFcpDataServiceHandler mCallBack;

	protected FcpDataServiceBase(Context pContext) {
		mContext = pContext;
		mAsyncHttpClient = new AsyncHttpClient();
		mAsyncHttpClient.setTimeout(SOCK_TIMEOUT);
		mAsyncHttpClient.setMaxRetriesAndTimeout(RETRY_TIMES, SOCK_TIMEOUT);
		mAsyncHttpClient.setUserAgent(getUserAgent());
	}

	public void cancel() {
		if (mAsyncHttpClient != null) {
			mAsyncHttpClient.cancelRequests(mContext, true);
		}
	}

	private String getUserAgent() {
		return USER_AGENT;
	}

	public AsyncHttpClient getAsyncHttpClient() {
		return mAsyncHttpClient;
	}

	protected Context getContext() {
		return mContext;
	}

	public void setDataServiceCallback(
			IFcpDataServiceHandler pDataServiceHandler) {
		this.mCallBack = pDataServiceHandler;
	}

	protected final IFcpDataServiceHandler getCallBack() {
		return mCallBack;
	}
	
	protected void HandleError(int errorCode, String errorMsg,
			Throwable errorThrowable) {
		try {
			if (getCallBack() != null) {
				getCallBack().onGetError(errorCode, errorMsg, errorThrowable);
			}
		} catch (Exception e) {
			logger.debug("HandleError", e);
		}
	}

	public abstract void get(Object pObject);

	protected abstract String getRequestURL(String url);

	public abstract void post(Object pObject);

}
